<template>
  <div class="index-analysis">
    <div class="main-select">
      <span class="main-select-title">指标统计分析</span>
      <a-select v-model="indexCode" @change="handleChange" placeholder="请选择指标" style="width: 240px">
        <a-select-option v-for="item in mainSelectList" :key="item.indexCode" :value="item.indexCode">{{
          item.indexName
        }}</a-select-option>
      </a-select>
    </div>
    <div class="content">
      <a-card title="决策流/策略集分析">
        <div class="date-select">
          <span class="date-select-title">决策流/策略集分析</span>
          <a-range-picker @change="handleDateChange" v-model="dateRange" format="YYYY-MM-DD" :ranges="dateRanges" />
        </div>
        <echart :option="chartOption" v-if="chartOption.series && chartOption.series.length > 0" />
        <div v-else>
          <a-empty description="暂无数据" />
        </div>
      </a-card>
      <a-card title="变化率分析" style="margin-top: 12px">
        <div class="date-select">
          <a-space>
            <span class="date-select-title">变化率分析</span>
            <a-select
              v-model="searchParams.workflowCode"
              placeholder="请选择关联决策流"
              style="width: 240px"
              allowClear
            >
              <a-select-option v-for="item in workflowList" :key="item.id" :value="item.workflowCode">{{
                item.workflowName
              }}</a-select-option>
            </a-select>
            <a-select v-model="searchParams.nodeType" placeholder="请选择节点类型" style="width: 240px" allowClear>
              <a-select-option v-for="item in nodeTypeList" :key="item.nodeType" :value="item.nodeType">{{
                item.nodeName
              }}</a-select-option>
            </a-select>
            <a-select v-model="searchParams.nodeId" placeholder="请选择关联节点" style="width: 240px" allowClear>
              <a-select-option v-for="item in nodeList" :key="item.nodeId" :value="item.nodeId">{{
                item.nodeName
              }}</a-select-option>
            </a-select>
          </a-space>
        </div>
        <a-row :gutter="24">
          <a-col :span="8">
            <div class="rate-content">
              <a-space>
                <span>当日同比变化率</span>
                <a-tooltip
                  title="与前一天比：【今日（00点->T点）A - 前一天（D-1的00点->T点）B】 / 前一天（D-1的00点->T点）B"
                >
                  <a-icon type="question-circle" />
                </a-tooltip>
                <a-select
                  v-model="todayEqualRate"
                  placeholder="请选择时间"
                  style="width: 120px"
                  @change="handleTodayEqualRateChange"
                >
                  <a-select-option v-for="item in dateList" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
                <a-tooltip :title="todayEqualDescription">
                  <a-icon type="info-circle" />
                </a-tooltip>
              </a-space>
            </div>
            <a-progress
              type="circle"
              :percent="todayEqualRateData"
              :format="() => `${todayEqualRateData}%`"
              :width="180"
              class="border"
            />
          </a-col>
          <a-col :span="8">
            <div class="rate-content">
              <a-space>
                <span>当日环比变化率</span>
                <a-tooltip title="环比（指当天）=【（T-1点->T点）A —（T-2点->T-1点）B】 /（T-2点->T-1点）B">
                  <a-icon type="question-circle" />
                </a-tooltip>
                <a-select
                  v-model="todayLoopRate"
                  placeholder="请选择时间"
                  style="width: 120px"
                  @change="handleTodayLoopRateChange"
                >
                  <a-select-option v-for="item in dateList" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
                <a-tooltip :title="todayLoopDescription">
                  <a-icon type="info-circle" />
                </a-tooltip>
              </a-space>
            </div>
            <a-progress
              type="circle"
              :percent="todayEqualRateData"
              :format="() => `${todayEqualRateData}%`"
              :width="180"
              class="border"
            />
          </a-col>
          <a-col :span="8">
            <div class="rate-content">
              <a-space>
                <span>上周同比变化率</span>
                <a-tooltip title="与上一周比：【前7天A — 前8-14天B】 / 前8-14天B">
                  <a-icon type="question-circle" />
                </a-tooltip>
                <a-tooltip :title="weekEqualDescription">
                  <a-icon type="info-circle" />
                </a-tooltip>
              </a-space>
            </div>
            <a-progress
              type="circle"
              :percent="weekEqualRateData"
              :format="() => `${weekEqualRateData}%`"
              :width="180"
            />
          </a-col>
        </a-row>
      </a-card>
    </div>
  </div>
</template>

<script>
import {
  getConditionList,
  getIndexStatistic,
  getWorkflowList,
  getNodeConfigList,
  getTodayEqualRate,
  getTodayLoopRate,
  getWeekEqualRate,
} from '@/api/indexAnalysis'
import { Echart } from '@/components'
import moment from 'moment'
const generateHourArray = () => {
  const hours = []
  for (let i = 0; i <= 24; i++) {
    hours.push(i.toString().padStart(2, '0'))
  }
  return hours
}
export default {
  name: 'IndexAnalysis',
  components: {
    Echart,
  },
  data() {
    return {
      mainSelectList: [],
      indexCode: '',
      dateRange: [],
      chartOption: {},
      searchParams: {},
      workflowList: [],
      nodeTypeList: [],
      nodeList: [],
      dateList: generateHourArray(),
      dayInfo: '',
      todayEqualDescription: '',
      todayEqualRate: undefined,
      todayEqualRateData: 0,
      todayLoopDescription: '',
      todayLoopRate: undefined,
      todayLoopRateData: 0,
      weekEqualDescription: '',
      weekEqualRateData: 0,
    }
  },
  computed: {
    dateRanges() {
      return {
        今日: [moment().startOf('day'), moment().endOf('day')],
        昨日: [moment().subtract(1, 'day').startOf('day'), moment().subtract(1, 'day').endOf('day')],
        最近7日: [moment().subtract(6, 'days').startOf('day'), moment().endOf('day')],
        最近30日: [moment().subtract(29, 'days').startOf('day'), moment().endOf('day')],
      }
    },
  },
  mounted() {
    // 设置默认时间区间为当前时间的前一周到当前时间,不包括第一天
    this.dateRange = [moment().subtract(7, 'days').add(1, 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
    this.init()
  },
  watch: {
    'searchParams.nodeType': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.nodeList = this.nodeTypeList.find((item) => item.nodeType === newVal)?.nodeList || []
        }
      },
    },
    searchParams: {
      handler(newVal, oldVal) {
        console.log('searchParams', newVal, oldVal)
        this.updateRate()
      },
      deep: true,
    },
  },
  methods: {
    init() {
      //   Promise.all([, getWorkflowList(), getNodeConfigList()]).then((res) => {
      //     const [conditionData, workflowData, nodeConfigData] = res
      //   })
      getConditionList().then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.mainSelectList = data.indices
          this.indexCode = data.indices[0]?.indexCode || ''
          this.updateEchart()
          this.updateRate()
        }
      })
      getWorkflowList().then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.workflowList = data
        }
      })
      getNodeConfigList().then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.nodeTypeList = data
        }
      })
    },
    updateEchart() {
      const params = {
        indexCode: this.indexCode,
        startTime: moment(this.dateRange[0]).unix() * 1000,
        endTime: moment(this.dateRange[1]).unix() * 1000,
      }
      getIndexStatistic(params).then((res) => {
        if (res?.statusCode === 200) {
          const {
            data: { items },
          } = res
          if (!items || items.length === 0) {
            this.chartOption = {}
            return
          }
          const legend = items.map((item) => item.workflowName)
          const series = items.map((item) => ({
            data: item.itemValues.map((itemValue) => itemValue.value),
            type: 'line',
            name: item.workflowName,
            smooth: true,
          }))
          const xAxisData = items[0]?.itemValues.map((item) => item.key)
          this.chartOption = {
            legend: {
              data: legend,
              right: '5%',
              top: '5%',
            },
            tooltip: {
              trigger: 'axis',
              formatter: function (params) {
                let result = params[0].name + '<br/>'
                params.forEach((param) => {
                  result += param.marker + ' ' + param.seriesName + ': ' + param.value + '<br/>'
                })
                return result
              },
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985',
                },
              },
            },
            series,
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxisData,
              axisLabel: {
                fontSize: 12,
              },
            },
            yAxis: {
              type: 'value',
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
            },
          }
        }
      })
    },
    handleChange(value) {
      this.indexCode = value
      this.updateEchart()
    },
    handleDateChange(value) {
      if (!value || !value[0] || !value[1]) {
        this.dateRange = value
        this.updateEchart()
        return
      }
      const startDate = moment(value[0])
      const endDate = moment(value[1])
      const daysDiff = endDate.diff(startDate, 'days')

      if (daysDiff > 30) {
        // 超过30日限制，显示提示并重置为最近30日
        this.$message.warning('时间区间不能超过30日，已自动调整为最近30日')
        this.dateRange = [moment().subtract(29, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      } else {
        this.dateRange = value
      }
      this.updateEchart()
    },
    updateRate() {
      this.handleTodayEqualRateChange(this.todayEqualRate)
      this.handleTodayLoopRateChange(this.todayLoopRate)
      this.handleWeekEqualRateChange()
    },
    handleTodayEqualRateChange(value) {
      this.todayEqualRate = value
      const params = {
        indexCode: this.indexCode,
        ...this.searchParams,
        hour: value,
      }
      if (!value) {
        delete params.hour
      } else {
        params.hour = Number(value)
      }
      getTodayEqualRate(params).then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.todayEqualDescription = data?.description
          this.todayEqualRateData = data?.value * 100 || 0
        }
      })
    },
    handleTodayLoopRateChange(value) {
      this.todayLoopRate = value
      const params = {
        indexCode: this.indexCode,
        ...this.searchParams,
        hour: Number(value),
      }
      if (!value) {
        delete params.hour
      } else {
        params.hour = Number(value)
      }

      getTodayLoopRate(params).then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.todayLoopDescription = data?.description
          this.todayLoopRateData = data?.value * 100 || 0
        }
      })
    },
    handleWeekEqualRateChange() {
      const params = {
        indexCode: this.indexCode,
        ...this.searchParams,
      }
      getWeekEqualRate(params).then((res) => {
        if (res?.statusCode === 200) {
          const { data } = res
          this.weekEqualDescription = data?.description
          this.weekEqualRateData = data?.value * 100
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.index-analysis {
  .main-select {
    padding: 0 16px;
    height: 48px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .main-select-title {
      display: inline-block;
      margin-right: 8px;
    }
  }
  .content {
    padding: 16px;
    .date-select {
      .date-select-title {
        display: inline-block;
        margin-right: 8px;
      }
    }
    :deep(.rate-content) {
      margin-top: 24px;
      text-align: center;
      height: 38px;
    }
    :deep(.ant-progress) {
      display: block;
      text-align: center;
      margin-top: 24px;
      &.border {
        border-right: 1px solid #f0f0f0;
      }
      .ant-progress-text {
        font-size: 32px;
        font-weight: 600;
        color: #000;
      }
    }
  }
}
</style>
